package com.lizi.idgenerator.utils;

import cn.hutool.core.util.StrUtil;
import com.lizi.idgenerator.service.impl.IdCreatorServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Struct;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * @author kingman
 * @since 2020-12-28 18:39
 */
public class CodeFormat {

    private static Logger log = LoggerFactory.getLogger(CodeFormat.class);

    private String[] sourcePatterns;
    private Calendar calendar = Calendar.getInstance();
    private int randomCodeSize = 0;

    public CodeFormat(String patterns)
    {
        if(StrUtil.isEmpty(patterns)){
            throw new IllegalArgumentException("参数patterns不能为空");
        }
        sourcePatterns = patterns.split(",");
        randomCodeSize = sourcePatterns.length;
    }


    /**
     * 与日期结合得到编码
     * @param date
     * @param code
     * @return
     */
    public String format(Date date,String code){

        calendar.setTime(date);

        // 获取年
        int year = calendar.get(Calendar.YEAR);
        // 获取月，这里需要需要月份的范围为0~11，因此获取月份的时候需要+1才是当前月份值
        int month = calendar.get(Calendar.MONTH) + 1;
        // 获取日
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        // 获取时 HOUR_OF_DAY:24小时表示,HOUR:12小时制
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
        // int hour = calendar.get(Calendar.HOUR_OF_DAY); // 24小时表示
        // 获取分
        int minute = calendar.get(Calendar.MINUTE);
        // 获取秒
        int second = calendar.get(Calendar.SECOND);

        String pattern = getPattern();
        pattern = pattern.replace("{yyyy}",String.valueOf(year));
        pattern = pattern.replace("{yy}",String.valueOf(year%1000));
        pattern = pattern.replace("{MM}",String.valueOf(month));
        pattern = pattern.replace("{dd}",String.valueOf(day));
        pattern = pattern.replace("{HH}",String.valueOf(hourOfDay));
        pattern = pattern.replace("{hh}",String.valueOf(hour));
        pattern = pattern.replace("{mm}",String.valueOf(minute));
        pattern = pattern.replace("{ss}",String.valueOf(second));
        pattern = pattern.replace("{code}",code);

        return pattern;
    }


    /**
     * 随机得到匹配参数
     * @return
     */
    private String getPattern(){
        if(randomCodeSize==1){
            return sourcePatterns[0];
        }
        int randomIndex = new Random().nextInt(randomCodeSize);
        return sourcePatterns[randomIndex];
    }
}
